import 'dart:async';
import 'dart:math';

import 'package:ac/common/style.dart';
import 'package:ac/data/ac_user_manager.dart';
import 'package:ac/widget/ac_gift_mixin.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:video_player/video_player.dart';
import 'package:visibility_detector/visibility_detector.dart';

import '../../model/ac_video_model.dart';
import 'ac_video_logic.dart';

class AcVideoPage extends StatelessWidget {
  final logic = Get.find<AcVideoLogic>();
  final state = Get.find<AcVideoLogic>().state;

  AcVideoPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Container(
      color: const Color(0xff100F0F),
      child: Stack(
        children: [
          _videoList(),
          Positioned(
            left: 20.w,
            top: 10 + ScreenUtil().statusBarHeight,
            child: Text(
              "Video",
              style: TextStyle(
                fontSize: 24.sp,
                color: Colors.white,
                fontWeight: FontWeight.w600,
                fontStyle: FontStyle.italic,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _videoList() {
    return Obx(() {
      return PageView.builder(
        scrollDirection: Axis.vertical,
        onPageChanged: (index) {
          state.currentIndex.value = index;
        },
        itemBuilder: (context, index) {
          return VideoItem(index: index);
        },
        itemCount: state.videoList.length,
      );
    });
  }
}

class VideoItem extends StatefulWidget {
  final int index;

  const VideoItem({super.key, required this.index});

  @override
  State<VideoItem> createState() => _VideoItemState();
}

class _VideoItemState extends State<VideoItem>
    with AcGiftMixin, SingleTickerProviderStateMixin {
  late VideoPlayerController _controller;
  late AcVideoModel _mediaModel;
  late AnimationController _animationController;
  late Timer _timer;
  String? _comment;
  TextEditingController commentController = TextEditingController();
  FocusNode commentFocusNode = FocusNode();

  bool _showComment = false;
  bool _animating = false;

  @override
  void initState() {
    super.initState();
    _initVideo();
    commentFocusNode.addListener(() {
      setState(() {
        _showComment = commentFocusNode.hasFocus;
      });
    });
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );
    _animationController.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        final logic = Get.find<AcVideoLogic>();
        Future.delayed(const Duration(seconds: 5)).then((value) {
          _animating = false;
          if (logic.state.commentList.isEmpty) {
            _comment = null;
            if (mounted) {
              setState(() {});
            }
          }
        });
      }
    });
    _timer = Timer.periodic(const Duration(milliseconds: 1000), (timer) {
      final logic = Get.find<AcVideoLogic>();
      if (logic.state.commentList.isNotEmpty && !_animating) {
        _comment = logic.state.commentList.removeAt(0);
        setState(() {});
        _animationController.reset();
        _animationController.forward();
        _animating = true;
      }
    });
  }

  @override
  void didUpdateWidget(covariant VideoItem oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);
    var video = Get.find<AcVideoLogic>().state.videoList[widget.index];
    if (video != _mediaModel) {
      _initVideo();
    }
  }

  void _initVideo() {
    _mediaModel = Get.find<AcVideoLogic>().state.videoList[widget.index];
    _controller = VideoPlayerController.networkUrl(Uri.parse(
      _mediaModel.mediaModel!.mediaUrl,
    ))
      ..initialize().then((_) {
        // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.
        if (mounted) setState(() {});
      })
      ..setLooping(true)
      ..addListener(() {
        debugPrint('video status: ${_controller.value}');
      });
  }

  @override
  void dispose() {
    _controller.dispose();
    _timer.cancel();
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Listener(
      onPointerUp: (event) {
        FocusScope.of(context).unfocus();
      },
      child: VisibilityDetector(
        key: Key("video_${widget.index}"),
        onVisibilityChanged: (VisibilityInfo info) {
          if (info.visibleFraction == 0) {
            if (mounted) {
              _controller.pause();
              setState(() {});
            }
          } else {
            _controller.play();
            setState(() {});
          }
        },
        child: GestureDetector(
          onTap: () {
            if (_showComment) return;
            setState(() {
              _controller.value.isPlaying
                  ? _controller.pause()
                  : _controller.play();
            });
          },
          child: Stack(
            children: [
              Center(
                child: _controller.value.isInitialized
                    ? AspectRatio(
                        aspectRatio: _controller.value.aspectRatio,
                        child: VideoPlayer(_controller),
                      )
                    : Container(),
              ),
              Align(
                alignment: Alignment.center,
                child: Visibility(
                  visible: !_controller.value.isPlaying,
                  child: Image.asset(
                    "images/icon_play.png",
                    width: 68.w,
                  ),
                ),
              ),
              Positioned(
                right: 20.w,
                bottom: 143.h,
                child: Column(
                  children: [
                    SizedBox(height: 242.h),
                    GestureDetector(
                      onTap: () {
                        setState(() {
                          _showComment = true;
                        });
                        commentFocusNode.requestFocus();
                      },
                      child: Image.asset(
                        "images/icon_comment.png",
                        width: 28.w,
                      ),
                    ),
                    SizedBox(height: 24.h),
                    GestureDetector(
                      onTap: () {
                        Get.find<AcVideoLogic>().likeVideo(widget.index);
                      },
                      child: Image.asset(
                        "images/icon_${_mediaModel.isLiked ? "like" : "dislike"}.png",
                        width: 28.w,
                      ),
                    ),
                    SizedBox(height: 24.h),
                    GestureDetector(
                      onTap: showRewardDialog,
                      child: Image.asset(
                        "images/icon_gift.png",
                        width: 28.w,
                      ),
                    ),
                  ],
                ),
              ),
              Positioned(
                left: 20.w,
                bottom: 150.h,
                child: Visibility(
                  visible: _comment != null,
                  child: SlideTransition(
                    position: Tween<Offset>(
                      begin: const Offset(0, 0.5),
                      end: const Offset(0, 0),
                    )
                        .chain(CurveTween(curve: Curves.easeIn))
                        .animate(_animationController),
                    child: Container(
                      height: 40.h,
                      width: 200.w,
                      padding: EdgeInsets.all(4.w),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(50.r),
                        gradient: LinearGradient(
                          colors: [
                            Colors.white.withOpacity(0.6),
                            Colors.transparent,
                          ],
                          begin: Alignment.centerLeft,
                          end: Alignment.centerRight,
                        ),
                      ),
                      child: Row(
                        children: [
                          ClipOval(
                            child: SizedBox(
                              width: 32.w,
                              height: 32.w,
                              child: CachedNetworkImage(
                                imageUrl: AcUserManager.userInfoModel?.userInfo
                                        .avatarThumbUrl ??
                                    "",
                                fit: BoxFit.cover,
                              ),
                            ),
                          ),
                          SizedBox(width: 12.w),
                          Text(
                            _comment ?? "",
                            style: TextStyle(
                              fontSize: 15.sp,
                              color: Colors.white,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ),
              Positioned(
                left: 20.w,
                bottom: 40.h,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      constraints: BoxConstraints(
                        maxWidth: 300.w,
                      ),
                      child: Text(
                        _mediaModel.text,
                        style: TextStyle(
                          fontSize: 16.sp,
                          color: Colors.white,
                        ),
                      ),
                    ),
                    SizedBox(height: 10.h),
                    Row(
                      children: [
                        ClipOval(
                          child: CachedNetworkImage(
                            imageUrl: _mediaModel.userInfo!.avatar ?? "",
                            width: 24.w,
                            height: 24.w,
                            fit: BoxFit.cover,
                          ),
                        ),
                        SizedBox(width: 8.w),
                        Text(
                          _mediaModel.userInfo!.nickname ?? "",
                          style: TextStyle(
                            fontSize: 14.sp,
                            color: Colors.white.withOpacity(0.8),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              Positioned(
                right: 20.w,
                top: 10 + ScreenUtil().statusBarHeight,
                child: GestureDetector(
                  onTap: () {
                    Get.find<AcVideoLogic>().more(widget.index, () {
                      _controller.pause();
                    });
                  },
                  child: Image.asset(
                    "images/icon_video_more.png",
                    width: 28.w,
                  ),
                ),
              ),
              Positioned(
                bottom: 0,
                child: Visibility(
                  visible: _showComment,
                  child: Container(
                    decoration: BoxDecoration(
                      color: Colors.white,
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.1),
                          offset: const Offset(0, -3),
                          blurRadius: 6.w,
                          spreadRadius: 0,
                        ),
                      ],
                    ),
                    child: SafeArea(
                      top: false,
                      child: Container(
                        height: 64.h,
                        width: 375.w,
                        alignment: Alignment.center,
                        padding: EdgeInsets.only(
                          left: 20.w,
                          right: 20.w,
                        ),
                        child: Row(
                          children: [
                            Container(
                              height: 36.h,
                              width: 335.w,
                              decoration: BoxDecoration(
                                color: const Color(0xfff2f2f2),
                                borderRadius: BorderRadius.circular(50.r),
                              ),
                              child: Row(
                                children: [
                                  Expanded(
                                    child: TextField(
                                      controller: commentController,
                                      focusNode: commentFocusNode,
                                      decoration: InputDecoration(
                                        hintText: "Enter your ideas...",
                                        hintStyle: TextStyle(
                                          fontSize: 14.sp,
                                          color:
                                              textColorBlack.withOpacity(0.3),
                                        ),
                                        contentPadding: EdgeInsets.only(
                                          left: 20.w,
                                          right: 20.w,
                                          top: 12.h,
                                          bottom: 12.h,
                                        ),
                                        border: InputBorder.none,
                                      ),
                                    ),
                                  ),
                                  SizedBox(width: 12.w),
                                  GestureDetector(
                                    onTap: () {
                                      var text = commentController.text;
                                      if (text.isEmpty) {
                                        return;
                                      }
                                      EasyLoading.show(
                                          status: 'sending...',
                                          maskType: EasyLoadingMaskType.black);
                                      Future.delayed(
                                          const Duration(milliseconds: 1300),
                                          () {
                                        EasyLoading.dismiss();
                                        commentController.clear();
                                        Get.find<AcVideoLogic>()
                                            .state
                                            .commentList
                                            .add(text);
                                      });
                                    },
                                    child: Container(
                                      height: 32.h,
                                      width: 32.w,
                                      alignment: Alignment.center,
                                      child:
                                          Image.asset("images/icon_send.png"),
                                    ),
                                  ),
                                  SizedBox(width: 2.w)
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
